package org.osite.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.NoSuchElementException;

import org.osite.xml.XmlMember;

public class Combination {
	
	private ArrayList<Series> data = ToolKit.newArrayList();
	private HashMap<String, String> nameMap = ToolKit.newHashMap();
	private boolean initialized = false;
	
	public Combination() {
	}
	
	@XmlMember(identifyByType = true)
	public void addSeries(Series series) {
		data.add(series);
	}
	
	public String get(String name) {
		String returned = nameMap.get(name);
		if (returned == null) {
			throw new NoSuchElementException(name);
		}
		return returned;
	}
	
	private boolean resetRest(int from) {
		for (int n = data.size(); from < n; ++from) {
			Series series = data.get(from);
			series.reset(this);
			if (!series.hasNext()) return false;
			nameMap.put(series.getName(), series.next());
		}
		return true;
	}
	
	public boolean next() {
		if (!initialized) {
			initialized = true;
			return resetRest(0);
		}
		
		for (int i = data.size() - 1; i >= 0; --i) {
			Series series = data.get(i);
			while (series.hasNext()) {
				nameMap.put(series.getName(), series.next());
				if (resetRest(i + 1)) return true;
			}
		}
		return false;
	}
}
